package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Answers;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import org.springframework.web.client.RestTemplate;


import java.util.*;
import java.util.stream.Collectors;

@Service
public class TodayBestService {

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;


    //注入TodayBestService
    @Autowired
    private TodayBestService todayBestService;

    /**
     * 查询今日佳人
     *
     * @return
     */
    public TodayBest queryTodayBest() {
        //校验token,通过sso的接口进行校验
        User user = UserThreadLocal.get();
        System.out.println(user.getId());
        //查询推荐用户（今日佳人）
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {//没查到的话,给一个默认的对象
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(100L);
        }

        //补全个人信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());
        if (null == userInfo) {
            return null;
        }
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "women");
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        todayBest.setAge(userInfo.getAge());

        return todayBest;
    }

    public TodayBest queryTodayBest(Long userId) {

        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if (score == 0) {
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    /**
     * 查询推荐列表
     *
     * @param param
     * @return
     */
    public PageResult queryRecommendation(RecommendUserQueryParam param) {
        //对token进行校验
        User user = UserThreadLocal.get();
        //创建一个pageResult对象,通过请求参数当中的内容对其进行赋值
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        //通过token校验完之后返回的id来进行调用RecommendUserService中的方法,返回一个PageInfo<RecommendUser>
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), param.getPage(), param.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //如果是空的话, 就查询默认的推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ",");
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId(user.getId());
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setScore(RandomUtils.nextDouble(70, 100));

                records.add(recommendUser);
            }
        }

        //获取pageInfo中的属性值rocords,通过遍历获取userId集合
        Set<Long> userIdList = records.stream().map(RecommendUser::getUserId).collect(Collectors.toSet());

        //通过这个集合和请求参数中包含的条件去查询到对应的推荐佳人列表userInfoList
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        /**
         * 以下是各种参数中传递的条件
         */
        queryWrapper.in("user_id", userIdList);//锁定为这些id
        //queryWrapper.eq("sex", StringUtils.equalsIgnoreCase(param.getGender(), "woman") ? 2 : 1);//对性别进行筛选查询
        if (StringUtils.isNotEmpty(param.getCity())) {
            //queryWrapper.like("city", param.getCity());
        }
        if (param.getAge() != null) {
            //queryWrapper.le("age", param.getAge());
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)) {
            //说明没有查到符合这些条件的用户信息
            return pageResult;
        }

        //通过遍历对todayBestList进行赋值
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();

            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());

            //设置缘分值
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == todayBest.getId().longValue()) {
                    double score = Math.floor(record.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBestList.add(todayBest);
        }
        //再通过缘分值对list进行排序
        //Collections.sort(todayBestList, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());
        Collections.sort(todayBestList, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());
        //将最后的todayBestList赋值给PageResult的item
        pageResult.setItems(todayBestList);
        return pageResult;
    }

    @Autowired
    private QuestionService questionService;

    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (question != null) {
            return question.getTxt();
        }

        return "";
    }

    @Value("${tanhua.sso.url}")
    private String url;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.url + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    public List<NearUserVo> queryNearUser(String gender, String distance) {
        // 查询当前用户的位置信息
        User user = UserThreadLocal.get();
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        // 根据当前用户的位置信息查询附近的好友
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        List<UserLocationVo> userLocationVoList = this.userLocationApi.queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));
        List<Long> userIds = userLocationVoList.stream().map(UserLocationVo::getUserId).collect(Collectors.toList());

        //通过id列表查询用户详细信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.in("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.in("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        /*
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        //如果性别相同则排除
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.in("sex", SexEnum.MAN);
        } else {
            queryWrapper.in("sex", SexEnum.WOMAN);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        */

        //筛选满足条件的
        List<UserInfo> userInfoList1 = userInfoList.stream().filter(s -> !s.getUserId().equals(user.getId())).collect(Collectors.toList());

        //进行遍历填充view object,并返回
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList1) {
            NearUserVo nearUserVo = new NearUserVo();

            nearUserVo.setUserId(userInfo.getUserId());
            nearUserVo.setAvatar(userInfo.getLogo());
            nearUserVo.setNickname(userInfo.getNickName());

            nearUserVoList.add(nearUserVo);
        }

        return nearUserVoList;
    }


    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, count);
        if (CollectionUtils.isEmpty(pageInfo.getRecords())) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                pageInfo.getRecords().add(recommendUser);
            }
        }

        List<RecommendUser> records = pageInfo.getRecords();
        int showCount = Math.min(10, records.size());

        List<RecommendUser> newRecommendUserList = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //随机选出推荐的好友
            createRecommendUser(newRecommendUserList, records);
        }

        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecommendUserList) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }

    /**
     * 递归随机生成推荐好友，保证不重复
     * @param newRecommendUserList
     * @param records
     */
    private void createRecommendUser(List<RecommendUser> newRecommendUserList, List<RecommendUser> records) {
        RecommendUser recommendUser = records.get(RandomUtils.nextInt(0, records.size() - 1));
        if (!newRecommendUserList.contains(recommendUser)) {
            newRecommendUserList.add(recommendUser);
        } else {
            // 开始递归
            createRecommendUser(newRecommendUserList, records);
        }
    }

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
    }
}
